package com.pt25.base.util;


import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 本地存储工具类
 * 本地缓存只适合缓存数据量不大的数据，太大数据会占用过多的服务器内存
 */
public class LocalCacheUtil {

    private static final Long defaultExpiredTimes = 60L;
    private static final Map<Long, Cache<String, Object>> localCacheMap = new HashMap<>();
    private static final Map<String, Long> localCacheExpiredSecondsMap = new HashMap<>();


    public static void saveLocalCache(String cacheKey, Object cacheValue) {
        saveLocalCache(cacheKey, cacheValue, defaultExpiredTimes);
    }

    public static void saveLocalCache(String cacheKey, Object cacheValue, Long expiredSeconds) {
        Cache<String, Object> cache = localCacheMap.get(expiredSeconds);
        if (cache == null) {
            synchronized (localCacheMap) {
                cache = localCacheMap.get(expiredSeconds);
                if (null == cache) {
                    localCacheMap.put(expiredSeconds, cache = CacheBuilder.newBuilder().expireAfterWrite(Duration.ofSeconds(expiredSeconds)).build());
                }
            }
        }
        localCacheExpiredSecondsMap.put(cacheKey, expiredSeconds);
        cache.put(cacheKey, cacheValue);
    }

    public static <T> T getLocalCache(String cacheKey, Class<T> clazz) {
        Long expiredTimes = localCacheExpiredSecondsMap.get(cacheKey);
        if (null == expiredTimes) {
            expiredTimes = defaultExpiredTimes;
        }
        Cache<String, Object> cache = localCacheMap.get(expiredTimes);
        if (null != cache) {
            Object object = cache.getIfPresent(cacheKey);
            if (null != object) {
                return JsonUtil.toBean(object, clazz);
            }
        }
        localCacheExpiredSecondsMap.remove(cacheKey);
        return null;
    }

    public static void delLocalCache(String cacheKey) {
        Long expiredTimes = localCacheExpiredSecondsMap.get(cacheKey);
        if (null == expiredTimes) {
            expiredTimes = defaultExpiredTimes;
        }
        Cache<String, Object> cache = localCacheMap.get(expiredTimes);
        if (null != cache) {
            cache.invalidate(cacheKey);
        }
        localCacheExpiredSecondsMap.remove(cacheKey);
    }
}
